﻿using STHPMS1.BLL.B_Core;
using STHPMS1.Common.C_Entity.Stmpms1;
using STHPMS1.ICore.I_BLL.Bus;
using STHPMS1.ICore.I_DAL;
using STHPMS1.ICore.I_Entity.Info;
using STHPMS1.ICore.I_Entity.PageModel;
using STHPMS1.ICore.I_Entity.Stmpms1;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
using System.Linq;
using STHPMS1.Common.C_Entity.PageModel;
using System.Dynamic;
using System.Collections;
using STHPMS1.Common.C_Enum;
using STHPMS1.Common.C_Extension;

namespace STHPMS1.BLL.B_Bus
{
    public class Dr_RepaircostBus : BllBase, IDr_RepaircostBill
    {
        public void Save<T>(T entity)
            where T : class ,IDr_Repaircost
        {
            if (this.Scene.Dal.Sthpms1.Update(entity) == 0)
            {
                this.Scene.Dal.Sthpms1.Insert(entity);
            }
        }

        public void Remove(IDr_Repaircost entity)
        {
            this.Scene.Dal.Sthpms1.Delete(entity);
        }

        public IEnumerable<T> Get<T>(Expression<Func<T, bool>> predicate, IPagingInfo info)
            where T : class, IDr_Repaircost
        {
            return this.Scene.Dal.Sthpms1.Select<T>(predicate, info);
        }


        public IComparePlanModel GetComparePlan(string proj_Id)
        {
            DataTable dt=this.Scene.Dal.Sthpms1.Dr_Repaircost.GetComparePlan(proj_Id);
            bool flag = true;
            if(dt.Rows.Count==0)
            {
                flag = false;
                dt=this.Scene.Dal.Sthpms1.Dr_Initialconstructioncost.GetComparePlan(proj_Id);
                dt.Columns.Add(new DataColumn("MAIN_YEAR", System.Type.GetType("System.Int32")));
                dt.Columns.Add(new DataColumn("MAINTYPE", System.Type.GetType("System.Int32")));
            }

            Dr_Decision_Tree decision=this.Scene.Dal.Sthpms1.Select<Dr_Decision_Tree>(p=>p.Proj_Id==proj_Id).FirstOrDefault();
            if(decision==null)throw new Exception("比选方案不存在 -"+proj_Id);

            List<PlanYearModel> yearList=null;
            List<PlanModel> planList= new List<PlanModel>();


            string INIPROJ_ID = "";
            PlanModel plan=null;
            foreach (DataRow dr in dt.Rows)
            {
                if(dr["INIPROJ_ID"].ToString()!=INIPROJ_ID)
                {
                    if (planList != null && plan != null && yearList!=null)
                    {
                        plan.ret=yearList.ToArray();
                    }
                    plan = new PlanModel();
                    plan.Analy_Period =(int) decision.Analy_Period;
                    plan.Iniproj_Id = dr["INIPROJ_ID"].ToString();
                    plan.Meas_Name = dr["MEAS_NAME"].ToString();
                    planList.Add(plan);
                    
                    yearList = new List<PlanYearModel>();
                    INIPROJ_ID = dr["INIPROJ_ID"].ToString();
                }

                if (flag)
                {
                    PlanYearModel year = new PlanYearModel();
                    year.year = Convert.ToInt32(dr["MAIN_YEAR"]);
                    year.type = Convert.ToInt32(dr["MAINTYPE"]);

                    yearList.Add(year);
                }
                else
                {
                    yearList = null;
                }               
            }
            if (planList != null && plan != null && yearList != null)
            {
                plan.ret = yearList.ToArray();
            }

            ComparePlanModel model = new ComparePlanModel();
            model.Proj_Id = proj_Id;
            model.plans = planList.ToArray();
            if (decision.Discou_Rate  !=null)  model.Discou_Rate =(double) decision.Discou_Rate;
            if (decision.Residu_Value != null) model.Residu_Value = (double)decision.Residu_Value;
            return model;
        }


        public void SaveAnalyCost(IComparePlanModel model)
        {
            if(model==null)throw new Exception("没有比选方案的数据!");

            ISthpms1Dao dao = this.Scene.Dal.Sthpms1;
            Dn_Divi_Result mainSeg = dao.Select<Dn_Divi_Result>(p => p.Mainsegid == model.Mainsegid).FirstOrDefault();
            if (mainSeg == null) throw new Exception("路段信息不存在 - "+model.Mainsegid);
            List<Dr_Maintainprice> priceList = dao.Select<Dr_Maintainprice>();
            if (priceList.Count == 0) throw new Exception("养护类型默认养护单价数据为空!");
            List<Dr_Repaircost> costList = new List<Dr_Repaircost>();

            Dictionary<string,double> SchecostList=new Dictionary<string,double>();
            short? analy_Period = 0;
            foreach (var plan in model.planArray)
            {
                if (string.IsNullOrEmpty(plan.Iniproj_Id)) throw new Exception("初选方案Id为空!");
                if (plan.retArray == null) continue;

                analy_Period =(short) plan.Analy_Period; 
                foreach (var item in plan.retArray)
                {
                    Dr_Maintainprice price = priceList.FirstOrDefault<Dr_Maintainprice>(p => p.Type == item.type && p.Rdclass_Dictid == mainSeg.Rdclass_Dictid);
                    if(price==null) throw new Exception("养护类型默认养护单价数据为空 -"+item.type);
                    if (mainSeg.Surfwidth == null) throw new Exception("养护路段的路面宽度为空 -" + mainSeg.Mainsegid);
                    
                    Dr_Repaircost cost = new Dr_Repaircost();
                    cost.Proj_Id = model.Proj_Id;
                    cost.Iniproj_Id = plan.Iniproj_Id;
                    cost.Main_Year = (short)item.year;
                    cost.Maintype = item.type;
                    cost.Schem_Uncost = price.Price;
                    cost.Amount = 1000 * mainSeg.Surfwidth;
                    cost.Annu_Maincost = cost.Schem_Uncost * cost.Amount * (mainSeg.Endmp - mainSeg.Beginmp);
                    costList.Add(cost);

                    if (SchecostList.ContainsKey(cost.Iniproj_Id))
                    {
                        SchecostList[cost.Iniproj_Id] += (double)cost.Annu_Maincost;
                    }else{
                        SchecostList.Add(cost.Iniproj_Id, (double)cost.Annu_Maincost);
                    }
                }
            }

            foreach (var item in costList)
	        {
                item.Schecost = SchecostList[item.Iniproj_Id];
	        }

            using (IDbTransaction tran = dao.BeginTransaction())
            {
                dao.Delete<Dr_Repaircost>(p => p.Proj_Id == model.Proj_Id);
                dao.Update<Dr_Decision_Tree>(new { Analy_Period = analy_Period, Discou_Rate = model.Discou_Rate, Residu_Value=model.Residu_Value }, p => p.Proj_Id == model.Proj_Id);
                if(costList.Count>0)  dao.InsertAll<Dr_Repaircost>(costList);
                tran.Commit();
            }
            
        }

        public dynamic GetRepairCost(string proj_Id)
        {
            dynamic data = new ArrayList();
            List<Dr_Repaircost> repairCostList = this.Scene.Dal.Sthpms1.Select<Dr_Repaircost>(p => p.Proj_Id == proj_Id);
            if (repairCostList.Count == 0) throw new Exception("比选方案的养护维修策略费用不存在 -"+proj_Id);

            Dr_Decision_Tree decision = this.Scene.Dal.Sthpms1.Select<Dr_Decision_Tree>(p => p.Proj_Id == proj_Id).FirstOrDefault();
            if (repairCostList.Count == 0) throw new Exception("比选方案不存在 -" + proj_Id);

            foreach (Dr_Repaircost repair in repairCostList)
            {
                Dr_Largemeas_Ini ini = this.Scene.Dal.Sthpms1.Select<Dr_Largemeas_Ini>(p => p.Iniproj_Id == repair.Iniproj_Id).FirstOrDefault();
                if (ini == null) throw new Exception("大中修初选方案不存在 - " + repair.Iniproj_Id);

                

                dynamic cost = new ExpandoObject();
                cost.Iniproj_Id = ini.Iniproj_Id;
                cost.Meas_Name = ini.Meas_Name;
                cost.Main_Year = repair.Main_Year;
                cost.Main_YearLabel =((DateTime)decision.Design_Time).Year+repair.Main_Year+"年";
                cost.Maintype = repair.Maintype;
                cost.Maintype_Label=((MainTypeEnum)repair.Maintype).GetEnumDescription();
                cost.Schem_Uncost = repair.Schem_Uncost;
                cost.Amount = repair.Amount;
                cost.Annu_Maincost = repair.Annu_Maincost/10000;//以万元为单位
                cost.Schecost = repair.Schecost/10000;//以万元为单位

                data.Add(cost);
            }

            return data;
        }

    }
}
